<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use think\admin\Controller;
use think\facade\Db;

/**
 * 超管系统-商品管理
 * Class Products
 * @package app\airobot\controller
 */
class TestProducts extends Controller
{
    private $table = 'robot_product';
    public $commonLogic;

    /**
     * 商品列表
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '商品列表';
        $query = $this->_query($this->table);
        $where = [];
        if (!empty($_GET['brand'])) {
            $where['brand'] = $_GET['brand'];
        }
        if (!empty($_GET['name'])) {
            $query->like($_GET['name']);
        }
        $query->where($where);
        $query->order('id asc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        $this->commonLogic = new CommonLogic();
        $ImageUrl = CommonLogic::GetImageUrl();

        foreach ($data as &$vo) {
            $vo = $this->dealDecimal($vo);
            if (strlen($vo['description']) > 80) {
                $vo['description'] = $this->commonLogic->TruncateString($vo['description'], 80) . "...";
            }
            $vo['amount'] = $this->commonLogic->DealAmount($vo['amount']);
            $vo['image'] = $ImageUrl['product'] . $vo['image'];
        }
    }

    /**
     * 导出文件
     * @auth true
     */
    public function export()
    {
        // 获取数据
        $this->commonLogic = new CommonLogic();
        $list = Db::table('robot_product')->select()->toArray();
        foreach ($list as &$vo) {
            // spin金额
            $vo = $this->dealDecimal($vo);
            // image
            $imageArr = explode("/", $vo['image']);
            $vo['image'] = end($imageArr);
        }

        // 设置 CSV 文件的名字
        $filename = "product.csv";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";');
        $output = fopen('php://output', 'w');

        // 写入 CSV 头部
        fputcsv($output, ['id', '品牌', '名称', '描述', '图片', '价格']);

        // 写入数据行
        foreach ($list as $k => $v) {
            fputcsv($output, [$v['id'], $v['brand'], $v['name'], $v['description'], $v['image'], $v['amount']]);
        }

        // 关闭输出流
        fclose($output);
    }

    public function dealDecimal($data)
    {
        foreach ($data as $key => $value) {
            if ($key == "amount") {
                $data[$key] = floatval($value);
            }
        }
        return $data;
    }
}